package com.example.ojdemo1.compile;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

public class CommandUtil {

    /**
     * @param cmd 进程要执行的命令
     * @param stdout 标准输出文件名 + 后缀
     * @param stderr 标准错误文件名 + 后缀
     * @return 进程等待后返回的状态码
     */
    public static int run(String cmd, String stdout, String stderr) {
        try {
            //1.获取 Runtime 实例，执行 exec 方法
            Runtime runtime = Runtime.getRuntime();
            Process process = runtime.exec(cmd);
            //2.获取 标准输出
            if(stdout != null) {
                InputStream stdoutFrom = process.getInputStream();
                FileOutputStream stdoutTo = new FileOutputStream(stdout);
                while(true) {
                    int read = stdoutFrom.read();
                    if(read == -1) {
                        break;
                    }
                    stdoutTo.write(read);
                }
                stdoutFrom.close();
                stdoutTo.close();
            }
            //3.获取 标准错误
            if(stderr != null) {
                InputStream stderrFrom = process.getErrorStream();
                FileOutputStream stderrTo = new FileOutputStream(stderr);
                while(true) {
                    int read = stderrFrom.read();
                    if(read == -1) {
                        break;
                    }
                    stderrTo.write(read);
                }
                stderrFrom.close();
                stderrTo.close();
            }
            //4.进程等待
            return process.waitFor();
        } catch (Exception e) {
            e.printStackTrace();
        }
        //返回异常的状态码
        return 1;
    }

    //测试
    public static void main(String[] args) {
        int result = run("javac", "stdout.txt", "stderr.txt");
        System.out.println(result);
    }

}
